package com.koron.css2.baseConfig.impl;

import com.koron.css2.ServerInterface;
import com.koron.css2.baseConfig.mapper.WaterTypeMapper;
import com.koron.css2.baseConfig.queryBean.WaterTypeQueryBean;
import com.koron.css2.baseConfig.vo.WaterTypeVO;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.TreeBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.util.Constant;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

import java.util.List;

/**
 * 用水类型树
 *
 * @author 廖大富
 */
public class WaterTypeTree implements ServerInterface {
    private static Logger logger = LogManager.getLogger(WaterTypeTree.class);

    @Override
    public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {

        MessageBean<TreeBean> info = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "success", TreeBean.class);
        try {
            WaterTypeMapper mapper = factory.getMapper(WaterTypeMapper.class);

            WaterTypeQueryBean selectBean = new WaterTypeQueryBean();
            selectBean.setStatus(1);//只查询启用的
            selectBean.setWaterTypeNo("all");
            List<WaterTypeVO> list = mapper.findWaterType(selectBean);
            TreeBean treeBean = new TreeBean();
            //创建根目录
            treeBean.setId("0");
            treeBean.setCode("");
            treeBean.setName("根目录");
            treeBean.setParent("");
            treeBean.setIsParent(true);
            //递归下级目录
            recTree(list, treeBean);

            info.setCode(Constant.MESSAGE_INT_SUCCESS);
            info.setDescription("success");
            info.setData(treeBean);
        } catch (Exception e) {
            info.setCode(Constant.MESSAGE_DBFAIL);
            info.setDescription("数据库异常");
            logger.error("数据库异常", e);
            factory.close(false);
        }
        return info;
    }

    /**
     * 递归查询下级目录树
     *
     * @param list
     * @param treeBean
     */
    private void recTree(List<WaterTypeVO> list, TreeBean treeBean) {
        for (WaterTypeVO bean : list) {
            //如果code是以父级开头，且长度多2位，说明这是他的下级
            if (bean.getWaterTypeNo().startsWith(treeBean.getCode()) && bean.getWaterTypeNo().length() == treeBean.getCode().length() + 2) {
                TreeBean b = new TreeBean();
                b.setId(bean.getId() + "");
                b.setCode(bean.getWaterTypeNo());
                b.setName(bean.getWaterTypeName());
                b.setParent(treeBean.getId() + "");
                b.setIsParent(false);
                treeBean.setIsParent(true);
                treeBean.getChildren().add(b);
                recTree(list, b); //递归循环下级目录
            }
        }
    }
}
